from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

"""
前端需要生成一个uuid，传递给后台，后台在生成图片和验证码然后在保存到redis中

1.接收参数
2.生成图片和验证记录码保存到redis中
3.返回响应

GET  /verificayions/imagecodes/(?P<image_code_id>.+)
"""
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
class RegisterImageCodeView(APIView):
    def get(self,request,image_code_id):
        # 1.接收参数
        # 2.生成图片
        text,image = captcha.generate_captcha()

        # 3.验证记录码保存到redis中
        redis_conn = get_redis_connection('code')
        from . import constants
        redis_conn.setex('img_%s'%image_code_id,constants.IMAGE_CODE_EXPIRE_TIIME,text)    #看到60秒，设置常量
        #setex  有效期


        # 4.返回响应
        return HttpResponse(image,content_type='image/jpeg')
        # return HttpResponse(image,content_type='application/json')

"""
前端在点击获取短信验证码的时候，前端需要将手机号，图片验证码内容，uuid传递给后端

1.获取参数
2.校验参数
3.获取短信验证码内容
4.发送短信
5.返回响应

GET   /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
"""
from verifications.serializers import RegisterSmsCodeSerializer
from libs.yuntongxun.sms import CCP
from random import randint
from rest_framework.response import Response

class RegisterSmsCodeView(APIView):
    def get(self,request,mobile):
        # 1.获取参数
        params=request.query_params
        # 2.校验参数

        serializer = RegisterSmsCodeSerializer(data=params)
        serializer.is_valid(raise_exception=True)

        # 3.获取短信验证码内容
        sms_code = '%06d'%randint(0,999999)

        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,300,sms_code)

        # 4.发送短信
        # CCP().ccp.send_template_sms(mobile, [sms_code, 5], 1)

        from celery_tasks.sms.tasks import send_sms_code

        # delay方法的参数　和　send_sms_code 的参数一一对应
        send_sms_code.delay(mobile,sms_code)

        # 5.返回响应
        return Response({'msg': 'OK'})